{% comment 'header' %}
# This file is part of opentaps Smart Energy Applications Suite (SEAS).

# opentaps Smart Energy Applications Suite (SEAS) is free software:
# you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# opentaps Smart Energy Applications Suite (SEAS) is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with opentaps Smart Energy Applications Suite (SEAS).
# If not, see <https://www.gnu.org/licenses/>.
{% endcomment %}

{% load static %}

<div id="meterhistorychart" v-cloak>
  <div class="card mb-3 border-nmd-0 m-n2 m-md-0" v-if="show">
    <div class="card-body p-md-3 p-0 mt-3 mt-md-0">
      <div class="row">
        <div class="col-12">
          <div class="row d-inline m-0 justify-content-center align-items-stretch">
            <apexchart
              ref="meter_history_line_chart"
              id="meter_history_line_chart"
              height=240
              type="line"
              :options="options"
              :series="series"></apexchart>
          </div>
          <div class="small text-muted text-right"><br></div>
        </div>
      </div>
    </div>
  </div>
  <div class="card mb-3 border-nmd-0 m-n2 m-md-0" v-if="!show" style="min-height: 255px;">
      <div class="text-center chart-spiner-placeholder">
        <b-spinner label="Loading..." variant="secondary"></b-spinner>
      </div>
  </div>
</div>

<div id="upload_modal">
  <upload-form-modal
    title="Upload Meter CSV/XML Data"
    usespinner="Y"
    :url="url"
    :csrfmiddlewaretoken="csrfmiddlewaretoken"></upload-form-modal>
</div>

<div id="solaredge_modal">
  <solaredge-form-modal
    title="Download from SolarEdge"
    usespinner="Y"
    :url="url"
    :csrfmiddlewaretoken="csrfmiddlewaretoken"></solaredge-form-modal>
</div>

<style>
#meterhistorychart {
  min-width: 50%;
  margin: 0 .5rem; 
}

.apexcharts-toolbar-custom-icon {
  height: 24px;
  width: 30px;
}
</style>

<script>
(function() {
  {% load js_csrf_token from core_tags %}
  const CSRF_TOKEN = '{% js_csrf_token %}';
  Vue.component('upload-form-modal', {
    delimiters: ['$[', ']'],
    extends: Vue.component('form-modal'),
    template: `
    <transition name="modal" v-if="visible">
      <div class="form-modal modal-mask">
        <div class="modal-wrapper">
          <div class="modal-container">

            <div class="modal-header">$[ title ] $[ title_name ]</div>

            <div class="modal-body">
              <div class="alert alert-danger" role="alert" v-if="errors.error">
                $[ errors.error ]
              </div>

              <b-form-group label="Import file type">
                <b-form-radio v-model="selectedFileType" name="selectedFileType" value="xml" @change="changeFileType">Greenbutton XML File</b-form-radio>
                <b-form-radio v-model="selectedFileType" name="selectedFileType" value="csv" @change="changeFileType">Meter History CSV File</b-form-radio>
              </b-form-group>

              <div class="mr-2 p-0 col flex-grow" style="min-width:7em;margin-bottom:1.5em;" v-if="selectedFileType == 'csv'">
                <v-select select-on-tab :options="uoms" v-model="currentUom" placeholder="unit of measures" :clearable="false" class="opt_w_auto">
                  <template slot="option" slot-scope="option">
                    $[ option.label ]&nbsp;<small>$[ option.description ] $[ option.kind ]</small>
                  </template>
                  <template slot="selected-option" slot-scope="option">
                    $[ option.label ]
                  </template>
                </v-select>
              </div>

              <div class="form-group" v-for="(field, idx) in fields">
                <input v-if="field.type == 'file'" type="file" :class="{'form-control':1, 'is-invalid': errors[field.key]}" :id="field.key" :name="field.key" :accept="field.accept" :placeholder="field.placeholder" @change="filesChange(field, $event.target.name, $event.target.files)"></input>
              </div>
            </div>

            <div class="modal-footer">
              <button class="modal-default-button btn btn-outline-danger" @click="closeModal">Cancel</button>
              <button v-if="!show_spinner" class="modal-default-button btn btn-outline-primary" @click="save">Upload</button>
              <b-spinner v-if="show_spinner" label="Loading..." variant="secondary"></b-spinner>
            </div>
          </div>
        </div>
      </div>
    </transition>
    `,
    data() {
      return {
        fields: [
          { key: 'meter_data', value: '', type: 'file', accept: '.xml' },
        ],
        selectedFileType: 'xml',
        uoms: [],
        currentUom: {value: 'energy_kWh', label: 'energy_kWh'},
      }
    },
    created: function () {
      console.log('Created upload modal ...');
      eventHub.$on('showModal_upload', this.showModal)
    },
    methods:{
      pre_save: function(formData, item) {
        formData.set('meter', '{{ meter_id }}')
        if (this.fields[0].value) {
          formData.append('meter_data', this.fields[0].value, this.fields[0].value.name);
        }
        if (this.currentUom) {
            formData.append('uom', this.currentUom.value);
        }
      },
      save_label: function(item) {
        return 'Upload'
      },
      post_save: function(response) {
        console.log('upload-form-modal: post_save', response)
        eventHub.$emit('meter_data_changed', {type: 'uploaded'})
      },
      post_show: function(item) {
        this.selectedFileType = 'xml';
        this.changeFileType(this.selectedFileType);
        this.currentUom = {value: 'energy_kWh', label: 'energy_kWh'};
        axios.get("{% url 'core:uom_restricted_list_json' 'energy_' %}")
          .then(x => x.data.items)
          .then(x => {
            for (var i=0;i<x.length;i++) {
              this.uoms.push({
                label: x[i].uom_id,
                description: x[i].description,
                value: x[i].uom_id,
                kind: x[i].type
              })
            }
          })
          .catch(err => {
            console.error('loading tags error :', err);
          });
      },
      changeFileType: function(checked) {
        console.log("changeFileType", checked);
        this.fields[0].accept = '.' + checked;
      }
    }
  });
  Vue.component('solaredge-form-modal', {
    delimiters: ['$[', ']'],
    extends: Vue.component('form-modal'),
    data() {
      return {
        fields: [
          { key: 'time_unit', label: 'Interval', value: 'HOUR', type: 'select', options:['HOUR', 'DAY', 'QUARTER_OF_AN_HOUR'] },
          { key: 'from_date', label: 'From', value: '{% if latest_meter_date %}{{ latest_meter_date }}{% endif %}', type: 'datetime' },
          { key: 'to_date', label: 'To', value: '', type: 'datetime' },
        ]
      }
    },
    created: function () {
      console.log('Created solaredge modal ...');
      eventHub.$on('showModal_solaredge', this.showModal)
    },
    methods:{
      post_show: function(item) {
        d = new Date();
        var datestring = d.getFullYear() + "-" +
                         ("0"+ (d.getMonth()+1)).slice(-2) + "-" +
                         ("0" + d.getDate()).slice(-2) + " " +
                         ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2) + ":00";

        this.fields[2].value = datestring;
        if (!this.fields[1].value) {
          d.setMonth(d.getMonth() - 1)
          var datestring2 = d.getFullYear() + "-" +
                           ("0"+ (d.getMonth()+1)).slice(-2) + "-" +
                           ("0" + d.getDate()).slice(-2) + " " +
                           ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2) + ":00";
          this.fields[1].value = datestring2;
        }
      },
      pre_save: function(formData, item) {
        formData.set('meter', '{{ meter_id }}')
        if (this.fields[0].value) {
          formData.append('time_unit', this.fields[0].value);
        }
        if (this.fields[1].value) {
          formData.append('from_date', this.fields[1].value);
        }
        if (this.fields[2].value) {
          formData.append('to_date', this.fields[2].value);
        }
      },
      save_label: function(item) {
        return 'Download'
      },
      post_save: function(response) {
        console.log('solaredge-form-modal: post_save', response)
        eventHub.$emit('meter_data_changed', {type: 'uploaded'})
      }
    }
  });
  new Vue({
    name: 'upload_modal',
    el: '#upload_modal',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        url: '{% url 'core:meter_data_import' meter_id %}',
      }
    }
  });
  new Vue({
    name: 'solaredge_modal',
    el: '#solaredge_modal',
    data() {
      return {
        csrfmiddlewaretoken: CSRF_TOKEN,
        url: '{% url 'core:meter_solaredge_data_import' meter_id %}',
      }
    }
  });

  // The global window.Apex variable below can be used to set common options for all charts on the page
  Apex = {
    dataLabels: {
      enabled: false
    },
    tooltip: {
      followCursor: false,
      theme: 'dark',
      x: {
        show: false
      },
      marker: {
        show: false
      },
    },
    grid: {
      clipMarkers: false
    },
  }
  var chartDegreeUnit = 'kWh'
  var myChart = new Vue({
    el: '#meterhistorychart',
    components: {
      apexchart: VueApexCharts,
    },
    data: function() {
      return {
        show: true,
        options: {
          chart: {
            id: 'meter-history-chart',
            toolbar: {
              tools: {
                download: false,
                selection: false,
                zoom: false,
                zoomin: false,
                zoomout: false,
                reset: false,
                pan: false,
                customIcons: [
                {
                  icon: '<i class="fa fa-plug"></i>',
                  title: 'Import UtilityAPI Data',
                  class: '',
                  click: function(e) {
                      window.open("{% url 'core:utilityapi_data_import' meter_id %}", "_self");
                  }
                },
                {% if is_solaredge %}
                  {
                    icon: '<i class="fa fa-cloud-download-alt"></i>',
                    title: 'Fetch SolarEdge Data',
                    class: '',
                    click: function(e) {
                      // Show form with upload options
                      console.log('Show solaredge download...');
                      eventHub.$emit('showModal_solaredge', {})
                    }
                  },
                {% else %}
                  {
                    icon: '<i class="fa fa-upload"></i>',
                    title: 'Upload',
                    class: '',
                    click: function(e) {
                      // Show form with upload options
                      console.log('Show upload...');
                      eventHub.$emit('showModal_upload', {})
                    }
                  },
                {% endif %}
                  {
                    icon: '<i class="fa fa-download"></i>',
                    title: 'Download',
                    class: '',
                    click: function(e) {
                      myChart.downloadAllData()
                    }
                  },
                ]
              },
            },
          },
          xaxis: {
            type: 'datetime',
            labels: {},
          },
          yaxis: {
            labels: {
              formatter: function(value) {
                return value.toFixed(1) + ' ' + chartDegreeUnit
              }
            },
          },
          tooltip: {
            x: {
              format: 'dd MMM yyyy HH:mm'
            }
          }
        },
        series: [{
          name: "Value",
          data: [
            {
              x: new Date().getTime(),
              y: 0
            },
          ],
          rawData: [
            0,
          ]
        }],
      }
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        this.refresh();
        eventHub.$on('meter_data_changed', this.refresh)
      },
      clear() {
        console.log('Clear charts.');
        // this.series.data.splice(0);
      },
      refresh() {
        this.fetchData();
      },
      getUrlArgs() {
        // placeholder to add custom parameters
        return '';
      },
      fetchData() {
        url = '{% url 'core:meter_data_json' meter_id %}' + this.getUrlArgs();
        console.log('Fetching meter chart from ', url);
        axios.get(url).then(response => {
          if (response.data.uom) {
            console.log('Fetching meter chart got UOM ', response.data.uom);
            chartDegreeUnit = response.data.uom.unit;
          }
          console.log('Fetching meter chart got ', response.data.values);
          if (response.data.values.length < 20) {
            this.$refs['meter_history_line_chart'].updateOptions({markers: {size: 5}});
          } else {
            this.$refs['meter_history_line_chart'].updateOptions({markers: {size: 0}});
          }
          if (response.data.values.length == 0) {
            this.series[0].data = [{y:0, x:new Date().getTime()}]
          } else {
            this.series[0].data = response.data.values.map(x => { return { y: x.value, x: parse_date(x.datetime).getTime() } } );
          }
          });
      },

      downloadAllData: function() {
          url = '{% url 'core:meter_data_json' meter_id %}'
          if (this.getUrlArgs() && this.getUrlArgs().length > 0) {
              url += this.getUrlArgs() + "&";
          } else {
              url += '?';
          }
          url += 'range=all';

          console.log('Fetching all meter chart from ', url);
          this.show = false;
          axios.get(url).then(response => {
              let lines = [];
              lines.push('Date/Time,Value (' + chartDegreeUnit + ')');

              if (response.data.values) {
                console.log('Fetching meter chart got ', response.data.values.length);
                for (let i = 0; i < response.data.values.length; i++) {
                  let date = new Date(response.data.values[i].datetime).toLocaleString()
                  lines.push(['"', date, '"', ',', response.data.values[i].value].join(''));
                }
              }

              saveTextAsCsvFile('Meter History.csv', lines.join('\n'));
              this.show = true;
          })
          .catch(err => {
            console.error('Fetching all meter data error :', err)
            this.show = true;
          });
      },

    }
  })
})();
</script>
